import { SendMSMCode } from "@/apis/user"
import type { CodeType } from "@/types/user"
import { showToast, type FormInstance } from "vant"
import { onUnmounted, ref, type Ref } from "vue"


// 
export function useMobileCode(mobile:Ref<string>,type:CodeType='login'){
  let timerId: number
  const form = ref<FormInstance>()
  const time = ref(0)
   const sendCode = async () => {
    if (time.value > 0) return
    await form.value?.validate('mobile')
    const res = await SendMSMCode(mobile.value, type)
    showToast('发送成功')
    time.value = 60
    //倒计时
    clearInterval(timerId)
    timerId = window.setInterval(() => {
      time.value--
      if (time.value <= 0) window.clearInterval(timerId)
    }, 1000)
    setTimeout(() => {
      showToast({
        message: res.data.code,
        duration: 4000
      })
    }, 3000)
    onUnmounted(() => {
      window.clearInterval(timerId)
    })
  }
  return{
    sendCode,
    time,
    form
  }
}
